import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/user'
const state = () => {
  return {
    // 用户令牌
    token: '',
    // 用户信息
    userInfo: {}
  }
}

const mutations = {
  // 设置token
  // 普通写法
  // setToken(state, token) {
  //   state.token = token
  // }
  // 箭头函数写法
  setToken: (state, token) => {
    state.token = token
  },
  // 清空token
  removeToken: (state) => {
    state.token = ''
  },
  // 设置用户信息
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // 清空用户信息
  removeUserInfo: (state) => {
    state.userInfo = {}
  }
}

const actions = {
  // 给token 赋值的异步操作:登录action
  loginAction: async({ commit }, loginForm) => {
    const resp = await loginAPI(loginForm)
    commit('setToken', resp.data)
  },
  getUserInfoAction: async({ commit }) => {
    // 解构 + 重命名
    const { data: userProfile } = await getUserProfileAPI()
    // console.log('userProfile', userProfile)
    // 基于此接口返回的userId继续发起第2次请求（获取用户头像等信息）
    const { data: userInfo } = await getUserInfoAPI(userProfile.userId)
    // console.log('data', userInfo)
    commit('setUserInfo', { ...userProfile, ...userInfo })
  },
  // 退出登录的action
  logoutAction: ({ commit }) => {
    commit('removeToken')
    commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
